package filters;

import helpers.UrlHelper;

import java.io.IOException;

import javax.management.relation.Role;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.data.RoleData;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import data.UserData;
import debugs.RoleDebug;

import models.RoleModel;
import models.StaffModel;
import models.UserModel;

public class AuthAdminFilter implements Filter {
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		//Check permission
		StaffModel staff = null;
		if (session.getAttribute("staff_logged_in") == null) {
			resp.sendRedirect("/staff/login");
			return;
		}
		
		staff = (StaffModel) session.getAttribute("staff_logged_in");
		RoleData roleData = new RoleData();
		RoleModel role = roleData.get(staff.getUsername());
		
		if (role == null) {
			resp.sendRedirect("/staff/msg/not-permission");
			return;
		}
		
		String servletPath = (String) req.getServletPath();
		boolean hasPermission = false;
		for (int i = 0; i < role.getPath().size(); i++) {
			if (role.getPath().get(i).equalsIgnoreCase("*")) {
				hasPermission = true;
			}
			if (role.getPath().get(i).equalsIgnoreCase(servletPath)) {
				hasPermission = true;
			}
			
			int length = servletPath.replaceAll("^"+role.getPath().get(i), "").length();
			if (servletPath.length() != length) {
				hasPermission = true;
			}
		}
		
		if (!hasPermission) {
			resp.sendRedirect("/staff/msg/not-permission");
			return;
		}
		
		chain.doFilter(request, response);
	}

	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}
